package org.dromara.common.encrypt.config

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties
import io.github.oshai.kotlinlogging.KotlinLogging
import org.dromara.common.encrypt.core.EncryptorManager
import org.dromara.common.encrypt.interceptor.MybatisDecryptInterceptor
import org.dromara.common.encrypt.interceptor.MybatisEncryptInterceptor
import org.dromara.common.encrypt.properties.EncryptorProperties
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean

/**
 * 加解密配置
 *
 * @author 老马
 * @version 4.6.0
 * @updater LikeYouDo
 * @date 2025/1/14 13:16
 */
@AutoConfiguration(after = [MybatisPlusAutoConfiguration::class])
@EnableConfigurationProperties(EncryptorProperties::class)
@ConditionalOnProperty(value = ["mybatis-encryptor.enable"], havingValue = "true")
class EncryptorAutoConfiguration(
    private val properties: EncryptorProperties
) {
    companion object {
        private val log = KotlinLogging.logger { }
    }

    @Bean
    fun encryptorManager(mybatisPlusProperties: MybatisPlusProperties): EncryptorManager {
        return EncryptorManager(mybatisPlusProperties.typeAliasesPackage)
    }

    @Bean
    fun mybatisEncryptInterceptor(encryptorManager: EncryptorManager): MybatisEncryptInterceptor {
        return MybatisEncryptInterceptor(encryptorManager, properties)
    }

    @Bean
    fun mybatisDecryptInterceptor(encryptorManager: EncryptorManager): MybatisDecryptInterceptor {
        return MybatisDecryptInterceptor(encryptorManager, properties)
    }
}
